const Koa = require('koa');
const co = require('co')
const nunjucksViews = require('koa-nunjucks-promise')
const router = require('koa-router')
const mount = require('koa-mount')
const server = require('koa-static')
const request = require('superagent'); //不要忘记npm install
const socketio = require('socket.io')

const koaBody = require('koa-body')();
const app = new Koa();

var http=require('http').Server(app.callback());
var io=require('socket.io').listen(http);

const route = new router();
var config=require('./config/app.config')
app.use(nunjucksViews(`${__dirname}/views`, { //配置模板文件路径，
    ext: 'html', //渲染文件后缀为 html
    noCache: process.env.NODE_ENV === 'development', //开发环境下不设置缓存
    watch: process.env.NODE_ENV === 'development', //开发环境下观察模板文件的变化并更新
    filters: { //过滤器  
        json: function(str) {
            return JSON.stringify(str, null, 2)
        }
    },
    globals: { //设置对于nunjucks的全局变量
        // staticPath: '//static'
    }
}))
app.use(mount('/static', server(`${__dirname}/public`))) //设置静态文件路径
route.get('/', co.wrap(function*(ctx) {
    yield ctx.render('index', { title: 'Nunjucks', content: 'Feifeiyu yeah!' })
}))
app.use(route.routes()).use(route.allowedMethods())
route.get('/route/test', co.wrap(function*(ctx) {
    ctx.body = 'feifeiyu nuaa'
}))
route.get('/index', co.wrap(function*(ctx) { 
    ctx.render('index', { title: 'Nunjucks', content: 'Feifeiyu yeah!' });
}))
const routers = require('./routers/index')
app.use(routers.routes()).use(routers.allowedMethods())


route.get('/getWxCode',co.wrap(function*(ctx) {
    /**
     * 正常用户的微信授权
     * 微信授权登陆完成重定向 
     * 1.获取授权code
     * 2、带上当前商户或平台的编号请求后台
     * 3、获取到微信授权用户信息重定向到首页进行缓存
     */
    console.log(ctx.query.code)
    var res = yield request
    .post(config.host+'/api/crm/weixin/getWxUser')
    .send({ customerId: '0', orgId: config.orgId, merchantId: config.merchantId, code: ctx.query.code })
    .set('X-API-Key', 'foobar')
    .set('Accept', 'application/json')
    .set('Content-Type', 'application/json');
    console.log('新生成的用户id');
    console.log(res.body.data.customerId);
    let id = res.body.data.customerId;
    ctx.response.redirect('http://qingwei.flyray.me/#/home?customerId='+id)
    //yield ctx.render('index', { customerId: '123875549725863936'});
}))

route.post('/weixin/jssdk/getShareParams', koaBody,co.wrap(function*(ctx) {
    // 添加观点
    let reqJson= ctx.request.body;
    reqJson['orgId']=config.orgId;
    reqJson['merchantId']=config.merchantId;
    var res = yield request
    .post(config.host+'/api/crm/weixin/jssdk/getShareParams')
    .send(reqJson)
    .set('X-API-Key', 'foobar')
    .set('Accept', 'application/json')
    .set('Content-Type', 'application/json');
    console.log(res.body);
    ctx.response.body = res.body;

}))

app.use(function *(){
    console.log(this.path);

    console.log(ctx.query.code)
    console.log(ctx.params.id)
    var res = yield request
    .post(config.host+'/api/crm/weixin/getWxUser')
    .send({ customerId: '0', orgId: config.orgId, merchantId: config.merchantId, code: ctx.query.code })
    .set('X-API-Key', 'foobar')
    .set('Accept', 'application/json')
    .set('Content-Type', 'application/json');
    console.log('新生成的用户id');
    console.log(res.body.data.customerId);
    let customerId = res.body.data.customerId;
    let bizId = ctx.params.id;
    if(this.path == "/home" || this.path == "/"){
        ctx.response.redirect('http://qingwei.flyray.me/#/home?customerId='+customerId)
    }else{
        ctx.response.redirect('http://qingwei.flyray.me/#'+this.path+'?customerId='+customerId+'id='+bizId)
    }
});

io.on('connection', function(socket){
    console.log('on connected!');
     //断开连接的事件
     socket.on('disconnect',function(){
        console.log('on connected!');
    });
    socket.on('message', function(message) {
      console.log(message);
      let info = ('http://www.flyray.me?t='+ Math.random())
      let color = '#'+Math.floor(Math.random() * 16777215).toString(16)
      let data = {info: info, color: color}
      io.emit("customEmit", data)
    });
  });

  http.listen(3000);
